/*
 * Example taken from resources
 * Original from Prof. Waters
 */


import java.io.IOException;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * This class implements a simple multi-threaded
 * server so that we can handle more than on client
 * at a time.
 *
 * @author Peter
 * @version 1.0
 */
public class Server {
    /** maximum concurrent connections */
    public static final int MAX_CONCURRENT_CONNECTIONS = 5;

    /** our thread pool */
    private final ExecutorService pool;

    /** the port to run on */
    private final int port;

    /**
     * Constructor for the class
     *
     * @param portP  the port to run on
     */
    public Server(final int portP) {
        port = portP;
        pool = Executors.newFixedThreadPool(MAX_CONCURRENT_CONNECTIONS);
    }

    /**
     * Main method, just run an instance
     * of the multi server
     *
     * @param args command line not used
     */
    public static void main(final String[] args) {
        final Server sms = new Server(45678); // $codepro.audit.disable numericLiterals
        sms.run();
    }

    /**
     * In the run method, we loop forever accepting client connections
     * and handling them.  This time, we make a thread instead of just
     * directly handling them.
     */
    public void run() {
        final ServerSocket theServer;
        Socket theClient = null;

        try {
            System.out.println("Starting Server");
            theServer = new ServerSocket(port);

            while (true) { // $codepro.audit.disable
                theClient = theServer.accept();

                ClientHandler chandle = new ClientHandler(theClient);
                pool.execute(chandle);
            }
        } catch (IOException e) {
            System.err.println("Error in Server Socket accept");
            e.printStackTrace();
        }
    }
    
    /**
     * Overrides toString() method
     * @return the server status
     */
    public String toString(){
    	return "";
    }
}
